package cn.conac.rc.gateway.modules.other.rest;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.MD5Utils;
import cn.conac.rc.framework.utils.ResponseUtils;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.gateway.modules.common.vo.UserVo;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.other.vo.OauthUserVO;
import cn.conac.rc.gateway.modules.user.entity.RcUserEntity;
import cn.conac.rc.gateway.modules.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@Api(tags = "oauth接口", description = "public/oauth")
public class OauthController {

    @Autowired
    OrganizationService organizationService;

    @Autowired
    UserService userService;

    /**
     * 用户头像路径的前缀
     */
    @Value("${file.user.img.path}")
    private String imgServerPathPrefix;

    /**
     * 默认用户头像的路径
     */
    @Value("${file.user.img.default.path}")
    private String defaultImgServerPath;

    @ApiOperation(value = "获取用户信息", notes = "返回oauth需要的用户信息,注意时间戳需要进行加密匹配，且与服务器时间误差不能超过10分钟", response = OauthUserVO.class)
    @RequestMapping(value = "public/oauth/getUserInfo", method = RequestMethod.POST)
    public ResponseEntity<ResultPojo> getUserInfo(HttpServletRequest request, HttpServletResponse response,
            @ApiParam("用户id") @RequestParam String userId, @ApiParam("时间戳") @RequestParam Long timestamp,
            @ApiParam("加密串") @RequestParam String token)

            throws Exception {
        ResultPojo result = new ResultPojo();

        result = validateTimeMD5(token, timestamp, result);
        if (result.getCode().equals(ResultPojo.CODE_SUCCESS)) {
            JSONObject result1 = userService.findByUserId(Integer.valueOf(userId));
            UserVo user = null;

            if (result1.getString("code").equals(ResultPojo.CODE_SUCCESS) && result1.getJSONObject("result") != null) {
                user = result1.getJSONObject("result").toJavaObject(UserVo.class);
                OauthUserVO oauthUser = new OauthUserVO(user);
                result.setResult(oauthUser);
                result.setCode(ResultPojo.CODE_SUCCESS);
            } else {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg("无法获取用户信息");
            }
        }

        return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);

    }

    @ApiOperation(value = "获取用户信息", notes = "返回二维码需要的用户信息接口,注意时间戳需要进行加密匹配，且与服务器时间误差不能超过10分钟", response = OauthUserVO.class)
    @RequestMapping(value = "public/oauth/getUserInfo2", method = RequestMethod.POST)
    public ResponseEntity<ResultPojo> getUserInfo2(HttpServletRequest request, HttpServletResponse response,
            @ApiParam("身份证号") @RequestParam String idnum, @ApiParam("姓名") @RequestParam(required = false) String name,
            @ApiParam("时间戳") @RequestParam Long timestamp, @ApiParam("加密串") @RequestParam String token)

            throws Exception {
        ResultPojo result = new ResultPojo();

        result = validateTimeMD5(token, timestamp, result);
        if (result.getCode().equals(ResultPojo.CODE_SUCCESS)) {
            JSONObject result1 = userService.findByIdNumber(idnum);
            UserVo user = null;
            if (result1.getString("code").equals(ResultPojo.CODE_SUCCESS) && result1.getJSONObject("result") != null) {
                user = result1.getJSONObject("result").toJavaObject(UserVo.class);
                OauthUserVO oauthUser = new OauthUserVO(user);
                // if (name.equals(name)) {
                result.setResult(oauthUser);
                result.setCode(ResultPojo.CODE_SUCCESS);
                // } else {
                // result.setCode(ResultPojo.CODE_FAILURE);
                // result.setMsg("用户信息不匹配");
                // }
            } else {
                result.setCode(ResultPojo.CODE_FAILURE);
                result.setMsg("无法获取用户信息");
            }
        }

        return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
    }

    /**
     * 校验md5值
     * @param uri 请求路径
     * @param token md5值
     * @param time 时间戳
     * @return 失败则修改result为失败状态，成功不对result进行修改
     */
    private static ResultPojo validateTimeMD5(String token, Long time, ResultPojo result) {
        if (time == -1) {
            return result;// TODO 用于方便测试联调
        }
        if (time == null || StringUtils.isBlank(token)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("缺少参数");
            return result;
        }
        long curTime = System.currentTimeMillis();
        if (Math.abs(curTime - time) > 600 * 1000) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("时间戳与服务器时间相差较大");
            return result;
        }
        MD5Utils encoderMd5 = new MD5Utils("conac-oauth", "MD5");// key{salt}
        String md5 = encoderMd5.encode(time + "");
        if (!md5.equalsIgnoreCase(token)) {
            result.setCode(ResultPojo.CODE_FAILURE);
            result.setMsg("时间戳加密校验失败");
            return result;
        }
        return result;
    }

    @ApiOperation(value = "根据用户ID获取用户头像信息", notes = "根据用户ID获取用户头像信息")
    @RequestMapping(value = "public/oauth/user/portrait/{userId}", method = RequestMethod.GET)
    public Object findUserPortraitInfoByUserId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "用户ID", required = true) @PathVariable("userId") Integer userId)
            throws RestClientException, Exception {
        ResultPojo resultInfo = new ResultPojo();
        if (null == userId) {
            // 参数baseId为null场合
            resultInfo.setCode(ResultPojo.CODE_FAILURE);
            resultInfo.setMsg("[ userId of parameter is null ] in function of findUserPortraitInfoByUserId "
                    + ResultPojo.MSG_FAILURE);
            resultInfo.setResult(null);
            return resultInfo;
        }

        JSONObject jsonUserInfo = userService.findByUserId(userId);
        if (ResultPojo.CODE_SUCCESS.equals(jsonUserInfo.getString("code"))) {

            RcUserEntity rcUserEntity = JSONObject.toJavaObject(jsonUserInfo.getJSONObject("result"),
                    RcUserEntity.class);
            // 设置绝对路径
            String absolutePath = StringUtils.isNotBlank(rcUserEntity.getAbsolutePath())
                    ? rcUserEntity.getAbsolutePath() : StringUtils.EMPTY;
            // 设置相对路径
            String relativePath = StringUtils.isNotBlank(rcUserEntity.getImgUrl()) ? rcUserEntity.getImgUrl()
                    : StringUtils.EMPTY;
            String imgFilePath = StringUtils.EMPTY;
            if (StringUtils.isNotBlank(relativePath) && relativePath.startsWith(imgServerPathPrefix)) {
                // 拼装完整路径
                imgFilePath = absolutePath + relativePath;
            } else {
                imgFilePath = absolutePath + defaultImgServerPath;
            }
            if (StringUtils.isNotBlank(imgFilePath)) {
                // 文件绝对路径获取
                File srcImgFile = new File(imgFilePath);
                if (srcImgFile.exists()) {
                    ResponseUtils.readImgData(request, response, srcImgFile);
                    return null;
                } else {
                    resultInfo.setCode(ResultPojo.CODE_FAILURE);
                    resultInfo.setMsg("读取用户头像文件不存在。 UserId：" + userId);
                    resultInfo.setResult(0);
                    return resultInfo;
                }
            } else {
                resultInfo.setCode(ResultPojo.CODE_FAILURE);
                resultInfo.setMsg("读取用户头像文件的路径不存在。 UserId：" + userId);
                resultInfo.setResult(0);
                return resultInfo;
            }
        } else {
            // 取得失败场合
            resultInfo.setCode(jsonUserInfo.getString("code"));
            resultInfo.setMsg("[userService.findByUserId] in function of findUserPortraitInfoByUserId "
                    + ResultPojo.MSG_FAILURE + "【" + jsonUserInfo.getString("msg") + "】");
            resultInfo.setResult(null);
            return resultInfo;
        }
    }

}
